using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace Charisma.Metadata
{
    public sealed class MetaFieldCollection : IndexedCollection<MetaField, string>
    {
        private readonly Dictionary<string, MetaField> aliasMap;

        public MetaFieldCollection()
            : base(p => p.Name)
        {
            aliasMap = new Dictionary<string, MetaField>();
        }

        public MetaField FindByAlias(string alias)
        {
            Contract.Requires(!String.IsNullOrEmpty(alias));

            MetaField result;
            if (aliasMap.TryGetValue(alias, out result))
                return result;
            return null;
        }

        protected override void OnAdd(MetaField item)
        {
            aliasMap.Add(item.Alias, item);
        }

        protected override void OnRemove(MetaField item)
        {
            aliasMap.Remove(item.Alias);
        }

        protected override void OnClear()
        {
            aliasMap.Clear();
        }
    }
}